package com.wrx.club_management_backend.controller;

import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.entity.Pic;
import com.wrx.club_management_backend.mapper.PicMapper;
import org.apache.coyote.ajp.AbstractAjpProtocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.codec.json.AbstractJackson2Decoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.wrx.club_management_backend.utils.RedisConstant.SYS_PIC;

@RestController
@RequestMapping("/pic")
public class PicController {

    @Autowired
    PicMapper picMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @PostMapping("/add")
    public AjaxResult add(@RequestBody Pic pic){
        int insert = picMapper.insert(pic);
        return AjaxResult.success("添加成功");
    }

    @PostMapping("/del/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        picMapper.deleteById(id);
        stringRedisTemplate.opsForSet().remove(SYS_PIC, id.toString());
        return AjaxResult.success("删除成功");
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody Pic pic){
        picMapper.updateById(pic);
        return AjaxResult.success("更新成功");
    }
    @GetMapping
    public AjaxResult list(){
        List<Pic> pics = picMapper.selectList(null);
        return AjaxResult.success(pics);
    }

    @PostMapping("/show/{id}")
    public AjaxResult show(@PathVariable("id") Long id){
        stringRedisTemplate.opsForSet().add(SYS_PIC, id.toString()); // 添加到展示列表中
        return AjaxResult.success("展示成功");
    }

    @PostMapping("fade/{id}")
    public AjaxResult fade(@PathVariable("id") Long id){
        stringRedisTemplate.opsForSet().remove(SYS_PIC, id.toString());
        return AjaxResult.success("取消展示");
    }

    @PostMapping("/getAllShow")
    public AjaxResult getAllShow(){
        Set<String> members = stringRedisTemplate.opsForSet().members(SYS_PIC);
        assert members != null;
        List<String> list = new ArrayList<>(members);
        List<Long> ids = list.stream().map(Long::parseLong).collect(Collectors.toList());
        List<Pic> pics = Collections.emptyList();
        if(!ids.isEmpty()) pics = picMapper.selectBatchIds(ids);
        return AjaxResult.success(pics);
    }
}
